<template>
  <MenuPage 
      :columns="columns"
      :data="list"
      :total="total"
      :page.sync="search.pageIndex"
      :size.sync="search.pageSize"
      :loading="loading"
      @queryFun="getQuestionnaire">
    <template slot="search">
        <Button type="primary" ghost @click="showAddAndUpdate('add')" class="md-add-jh"
          >创建{{pageBtnTxt}}</Button
        >
        <Divider type="vertical" />
        <div style="height: 32px;line-height: 32px;flex-shrink: 0;">
          <Checkbox v-model="creatByMeModal" @on-change="getQuestionnaire(1)">由我创建</Checkbox>
        </div>
        <Input
          v-model.trim="search.name"
          clearable
          placeholder="问卷名称"
          style="width: 180px;margin-left: 15px"
          @on-change="getQuestionnaire(1)"
        />
        <Button
          class="header-btn"
          type="primary"
          ghost
          style="height: 32px;margin-left: 5px;"
          @click="refreshSurveyContentList()"
          ><i class="el-icon-refresh-right"
        /></Button>
      </template>
    <Modal
      v-model="modal.show"
      :title="modal.title"
      :loading="modal.loading"
      :mask-closable="false"
      :footer-hide="true"
    >
      <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="96">
        <FormItem label="问卷名称" prop="name" key="name">
          <Input v-model.trim="formValidate.name" placeholder="题目名称长度为1-128个字符"></Input>
        </FormItem>
        <FormItem label="演练场景" key="sceneId">
          <Select filterable v-model="formValidate.sceneId" placeholder="选择场景" filterable>
            <Option
              v-for="item in sceneIdList"
              :key="item.id"
              :value="item.id"
              :title="item.name"
              >{{ item.name }}</Option
            >
          </Select>
        </FormItem>
        <FormItem label="描述" prop="description" key="description">
          <Input
            v-model.trim="formValidate.description"
            type="textarea"
            :maxlength="200"
            :autosize="{ minRows: 2, maxRows: 5 }"
            placeholder="描述信息"
          ></Input>
        </FormItem>
        <FormItem>
          <Button type="primary" @click="formBtn()">确定</Button>
          <Button @click="handleReset()" style="margin-left: 8px">重置</Button>
        </FormItem>
      </Form>
    </Modal>
    <Modal
      v-model="contentModal.show"
      :title="contentModal.title"
      :mask-closable="false"
      :footer-hide="true"
      width="1000"
    >
      <div style="display:flex; height: calc(100vh - 200px);">
        <QuestionList
          :data="objList"
          @mod-subject="modSubject"
          @del-subject="delSubject"
          style="display:inline-block; width:480px; height: 100%; overflow: auto; margin-right: 20px;"
        >
        </QuestionList>
        <Form
          ref="contentFormValidate"
          :model="ContentDto"
          :rules="contentruleValidate"
          :label-width="96"
          style="width:500px;display:inline-block; height: 100%;"
        >
          <div class="class-title-wrap">
            <div class="class-title">
              <div class="class-title-all" @click="clicktab('add')" :class="{ active: isadd }">
                创建
              </div>
              <!--<div class="class-title-line" :class="{'line-active':allClassLine}"></div>-->
            </div>
            <div style="margin-left:30px" class="class-title">
              <!--<Badge :count="myClassLen"></Badge>-->
              <div class="class-title-all" :class="{ active: !isadd }">修改</div>
              <!--<div class="class-title-line" :class="{'line-active':myClassLine}"></div>-->
            </div>
          </div>
          <Divider dashed />
          <div style="max-height: calc(100% - 116px); overflow: auto;">
            <FormItem label="题目类型" prop="type">
              <Select filterable
                v-model="ContentDto.type"
                placeholder="选择题目类型"
                @on-change="changeAnswerTxt"
                transfer
                style="width:200px"
              >
                <Option :value="0">单选</Option>
                <Option :value="1">多选</Option>
                <Option :value="2">问答</Option>
              </Select>
            </FormItem>
            <FormItem label="题目名称" prop="description" key="description">
              <Input
                v-model.trim="ContentDto.description"
                placeholder="题目名称长度为1-128个字符"
              ></Input>
            </FormItem>
            <!-- <FormItem label="题目答案" prop="options" key="options" v-if="ContentDto.type=='2'">
                            <Input v-model.trim="ContentDto.options.description" placeholder="请输入题目答案"></Input>
                        </FormItem> -->
            <FormItem
              v-for="(item, index) in ContentDto.options"
              v-if="ContentDto.type === 0 || ContentDto.type === 1"
              :key="index"
              :label="'[' + filterIndex(index + 1) + ']'"
              :prop="'options.' + index + '.description'"
              :rules="{ required: true, message: '题目答案不能为空', trigger: 'change' }"
              class="answerForm"
            >
              <Row>
                <Col span="18">
                  <Input
                    v-model.trim="item.description"
                    type="textarea"
                    :maxlength="200"
                    :rows="2"
                    placeholder="请输入题目答案"
                    style="margin-bottom:12px"
                  />
                  <!-- <Input v-model.trim="item.explanation" type="text"  placeholder="请输入题目正确答案" />-->
                </Col>
                <Col span="4" offset="1">
                  <span
                    v-if="
                      (ContentDto.type === 0 || ContentDto.type === 1) &&
                        ContentDto.options.length > 1
                    "
                    ><Button @click="handleRemove(index,item)">删除</Button></span
                  >
                </Col>
              </Row>
            </FormItem>
            <FormItem style="margin-top:0" v-if="ContentDto.type === 1 || ContentDto.type === 0">
              <Button type="primary" @click="addAnswers(ContentDto,!isadd)">增加</Button>
            </FormItem>
          </div>
          <FormItem>
            <Button type="primary" @click="contentBtn()">确定</Button>
            <Button @click="handleReset1()" style="margin-left: 8px">重置</Button>
          </FormItem>
        </Form>
      </div>
    </Modal>
    <Modal v-model="delDrillModal" width="300">
      <p slot="header" style="color:#f60">
        <Icon type="ios-information-circle-outline"></Icon>
        <span>确认删除</span>
      </p>
      <div slot="footer">
        <Button type="default" @click="closeDelModal">取消</Button>
        <Button type="error" @click="delScene">删除</Button>
      </div>
    </Modal>
    <Modal v-model="statisticsModal" :title="statisticsTitle" :footer-hide="true">
      <QuestionList
        :data="statisticsList"
        :joined="joined"
        :isDetail="true"
        style="display:inline-block;width:500px"
      />
    </Modal>
  </MenuPage>
</template>

<script>
import { getaccessgrouplist } from '@/api/access_new';
import { getSceneList } from '@/api/drill_compete';
import QuestionList from '@/components/question-list-qt/question-list.vue';
import encryption from '@/libs/encryption.js';
import {
  getQuestionnaireSurveyList,
  createQuestionnaireSurvey,
  updateQuestionnaireSurvey,
  deleteQuestionnaireSurvey,
  getSurveyContentList,
  createSurveyContent,
  updateSurveyContent,
  deleteSurveyContent,
  getQuestionnaireStatistics,
  deleteContentOption
} from '@/api/questionnaire-survey';
import {validateName1,validateName128 } from '@/libs/reg.js'
import pageTitle from '@/mixin/pageTitle';
export default {
  components: {
    QuestionList
  },
  mixins:[pageTitle],
  data() {
    const validateName = (rule, value, callback) => {
      var reg = /[\\:：*?？"<>|;；,，+=]/gi;
      //验证警戒值
      if (value) {
        if (reg.test(value)) {
          callback(new Error('名称不能包含下列任意字符 \\ : * ? " < > | ; , + ='));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    return {
      userList: [],
      sceneIdList: [],
      querySceneInfo: {
        pageIndex: 1,
        pageSize: 9999,
        order: 'desc',
        sortBy: 'createTime',
        progress: '4'
      },
      creatByMeModal: false,
      statisticsList: [],
      joined: 0,
      statisticsModal: false,
      statisticsTitle: '',
      isadd: true,
      delDrillModal: false,
      showList: {},
      objTotal: 0,
      objList: [],
      delQuestionnaireId: '',
      questionnaireId: '',
      USER_ID: '',
      USER_Name: '',
      search: {
        name: '',
        pageIndex: 1,
        pageSize: 10
      },
      showDefImg: false,
      list: [],
      total: 0,
      loading:false,
      memsIcon1: require('../../assets/project/mems-h.png'),
      memsIcon2: require('../../assets/project/mems-d.png'),
      contentModal: {
        show: false,
        title: '',
        isAdd: true
        // loading: false
      },
      index: 1, //题目顺序
      optionsIndex: 1, //选项顺序
      modal: {
        show: false,
        title: '',
        isAdd: true,
        loading: false
      },
      formValidate: {
        name: '',
        description: '',
        available: 0,
        sceneId: ''
      },
      ContentDto: {
        description: '',
        label: 0,
        type: '',
        questionnaireId: '',
        options: [
          {
            description: '',
            label: 0,
            questionnaireId: ''
          }
        ]
      },
      ruleValidate: {
        name: [
          { required: true, max: 128, message: '问卷名称长度为1-128个字符', trigger: 'change' },
          { validator: validateName128, trigger: 'change' }
        ],
        description: [{ required: true, message: '不能为空', trigger: 'change' }],
        available: [{ required: true, type: 'number', message: '不能为空', trigger: 'change' }]
      },
      contentruleValidate: {
        description: [
          { required: true, max: 128, message: '题目长度为1-128个字符', trigger: 'change' },
          { validator: validateName128, trigger: 'change' }
        ],
        options: [{ required: true, message: '不能为空', trigger: 'change' }],
        modeCode: [
          {
            required: true,
            type: 'number',
            message: '类型不能为空',
            trigger: 'change'
          }
        ]
      },
      columns: [
        {
          type:'link',
          placement: 'top-left',
          title: '问卷名称',
          key: 'name',
          align: 'center',
          tooltip: true,
          minWidth: 260,
          fun:(data) => {
            this.getQuestionnaireStatistics(data.id, data.name);
          }
        },
        {
          type:'link',
          placement: 'top-left',
          title: '演练场景',
          key: 'sceneName',
          align: 'center',
          tooltip: true,
          minWidth: 200,
          fun: (data) => {
            this.goSceneDetail(data.sceneId, data.sceneName);
          }
        },
        {
          title: '是否可用',
          key: 'isQuestion',
          align: 'center',
          placement: 'top-right',
          minWidth: 100,
          render: (h, params) => {
            return h(
              'Tag',
              {
                props: {
                  color: params.row.available == 0 ? 'var(--status-no)' : 'var(--status-yes)'
                }
              },
              params.row.available == 0 ? '否' : '是'
            );
          }
        },
        {
          title: '创建者',
          key: 'creatorName',
          align: 'center',
          minWidth: 150,
          tooltip: true
        },
        {
          title: '创建时间',
          key: 'createTime',
          align: 'center',
          minWidth: 140,
          tooltip: true
        },
        {
          title: '描述',
          key: 'description',
          align: 'center',
          minWidth: 200,
          tooltip: true
        },
        {
          title: '操作',
          minWidth: 280,
          fixed: 'right',
          placement: 'top-right',
          key:'action',
          opList:[
            {
              txt:(data) => {
                return data.available == 1 ? '禁用' : '启用'
              },
              disabled:(data) => {
                (!this.isRootDesigner && data.creator != this.USER_ID) ||
                data.collect
              },
              tooltip:true,
              title:(data) => {
                return data.available == 1 ? '确认禁用？' : '确认启用？'
              },
              on: {
                click: (row,e) => {
                  getSurveyContentList({
                    questionnaireId: row.id
                  }).then(({ code, data = {} }) => {
                    if (code === 1 && data.total > 0) {
                      // 有数据才允许修改，否则不允许设置
                      let passObj = { ...row };
                      passObj.available = row.available ? 0 : 1;
                      const txt = row.available == 0 ? '开启' : '关闭';
                      updateQuestionnaireSurvey(passObj).then((res) => {
                        if (res.code == 1) {
                          this.$Message.info(txt + '完成');
                          this.getQuestionnaire(this.pageIndex);
                        } else {
                          this.$Message.error(res.message);
                        }
                      });
                    } else {
                      row.available = !row.available;
                      this.$Message.warning('没有问卷试题，无法设置是否可用');
                      return;
                    }
                  });
                }
              }
            },
            {
              txt:'修改',
              disabled:this.setReBtnStatus,
              on: {
                click: (data,e) => {
                  this.showAddAndUpdate('mod', data);
                }
              }
            },{
              txt:'问卷内容',
              disabled:this.setReBtnStatus,
              on: {
                click: (data,e) => {
                  this.showAddContent(data);
                }
              }
            },{
              txt:'删除',
              type:"delete",
              tooltip:true,
              title:'你确定要删除吗?',
              disabled: (data) => {
                return data.creator != this.USER_ID
              },
              on: {
                click: (data,e) => {
                  this.delQuestionnaireSurvey(data.id);
                }
              }
            },
            {
              txt:'用户管理',
              disabled: (data) => {
                return this.setReBtnStatus(data) || data.available != 1
              },
              on: {
                click: (data,e) => {
                  this.membersManage(data);
                }
              }
            }
          ],
        }
      ]
    };
  },
  created() {
    // 获取用户id
    let November = sessionStorage.getItem('November');
    November = JSON.parse(encryption.SelfUseDecrypt(November));
    this.USER_ID = November.userId;
    this.isRootDesigner = November.isRootDesigner;
    this.userName = November.userName;
    this.isRetainer = sessionStorage.getItem('isRetainer') === 'true';
  },
  mounted() {
    this.getQuestionnaire();
  },
  methods: {
    goSceneDetail(id,name) {
      console.log('id',id)
      console.log('name',name)
      getSceneList({id: id}).then(res => {
        console.log('场景列表',res)
        if(res.code == 1 && res.data.items.length > 0) {
          let item = res.data.items[0]
          this.toDetailPage(item)
        }else {
          this.$Message.error('不存在改场景')
        }
      })
    },
    toDetailPage(item) {
      console.log( JSON.parse(item.extension));
      let extension;
      try {
        extension = JSON.parse(item.extension);
      } catch (e) {
        extension = {};
      }
      const deploymentType = extension.deploymentType;
      if (![2, 4].includes(item.progress)) {
        // 非结束、进行中的状态，需要看工程状态判断能不能进入场景详情页
        if (
          item.deployStatus != 3 || // 部署成功允许进入，部署清空后处于未部署状态，也允许进入
          (deploymentType && ['error', 'deploying', 'queryError'].includes(item.quickCreateStatus))
        ) {
          //
          this.$Message.warning('未部署成功不可进入！');
          return;
        }
      }
      if (item.progress == 2) {
        if (
          [0, 1, 2, 9].includes(item.deployStatus) ||
          (deploymentType && item.quickCreateStatus === 'deploying')
        ) {
          this.$Message.warning('工程部署中不可进入！');
          return;
        }
      }
      if (!item.startTime || !item.endTime) {
        if (this.setBtnStatus(item, 'modify')) {
          this.$Message.warning('未设置竞赛起止时间不可进入！');
        }
        return;
      }
      if (item.projectId) {
        this.toDetailPage(item);
      } else {
        this.$Message.warning('工程不存在！');
      }
    },
    toDetailPage(params) {
      const extensionObj =  JSON.parse( params.extension)
      let path;
      switch (Number.parseInt(params.type)) {
          case 0:
              path = '/awdDrillDetail';
              break;
          case 4:
              path = '/stDrillDetail';
              break;
          case 7:
              path = '/multipleDrillDetail';
              break;
      }
      if (path) {
        this.$router.push({
          path: path,
          query: {
            id: params.id, //场景id
            prjid: params.projectId, //工程id
            name: params.name,
            page: this.querySceneInfo.page || this.querySceneInfo.pageIndex,
            vmInEnable: JSON.parse(params.extension).vmInEnable,
            path:this.title,
            teamIpCount:extensionObj.teamIpCount,
            isQuestion: true,
          },
        });
      }
    },
    getaccessgrouplist() {
      let param = {
        pageIndex: 1,
        pageSize: 9999,
        testId: this.formValidate.sceneId
      };
      getaccessgrouplist(param).then((res) => {
        if (res.code == 1) {
          let group = res.data.items;
          if (group.length > 0) {
            for (var i = 0; i < group.length; i++) {
              this.userList = this.userList.concat(group[i].userList);
            }
            // if(this)
            console.log(this.userList, 'this.userListthis.userList');
          }
        }
      });
    },
    getSceneList() {
      getSceneList(this.querySceneInfo).then((res) => {
        if (res.code == 1) {
          this.sceneIdList = res.data.items;
          if (this.sceneIdList.length > 0) {
            this.sceneIdList = this.sceneIdList.filter(
              (item) => item.type == 4 || item.type == 7 || item.type == 0
            );
          }
        } else {
          this.$Message.warning('查询场景失败');
        }
      });
    },
    getQuestionnaireStatistics(id, name) {
      getQuestionnaireStatistics(id)
        .then(({ code, message, data }) => {
          if (code !== 1) {
            this.$Message.warning(message);
            return;
          }
          this.statisticsModal = true;
          this.statisticsTitle = name;
          let list = data.contents || [];
          let joined = data.joined;
          this.statisticsList = list.map((item) => {
            item.analysis.forEach((items) => {
              this.$set(items, 'no', items.label);
              this.$set(
                items,
                'percent',
                joined === 0 ? 0 : Number(((items.joined / joined) * 100).toFixed(2))
              );
            });
            this.$set(item, 'answers', item.analysis);
            this.$set(item, 'name', item.description);
            if (item.type === 0) {
              this.$set(item, 'modeCode', 1);
            } else if (item.type === 2) {
              this.$set(item, 'modeCode', 6);
              this.$set(item, 'description', item.description);
            } else {
              this.$set(item, 'modeCode', 2);
            }
            return item;
          });
          this.joined = joined;
        })
        .catch(() => {
          this.$Message.error('获取问卷调查提交详情异常');
        });
    },
    clicktab(type) {
      if (type === 'add') {
        (this.isadd = true), this.handleReset1();
        this.initContentData();
      } else {
        (this.isadd = false), this.handleReset1();
      }
    },
    closeDelModal() {
      this.delDrillModal = false;
    },
    delSubject(item) {
      this.delDrillModal = true;
      this.delQuestionnaireId = item.id;
    },
    modSubject(item) {
      let itemCopy = JSON.parse(JSON.stringify(item))
      let options = itemCopy.options
      if(itemCopy.type === 0 || itemCopy.type === 1) {
        options.forEach(ele => {
          ele.description = ele.description.substr(3)
        })
      }
      this.isadd = false
      this.ContentDto = {
        description: itemCopy.description,
        label: itemCopy.label,
        type: itemCopy.type,
        id: itemCopy.id,
        questionnaireId: itemCopy.questionnaireId,
        options: options
      }
    },
    delScene() {
      deleteSurveyContent(this.delQuestionnaireId).then((res) => {
        if (res.code == 1) {
          this.$Message.success('删除成功');
        } else {
          this.$Message.warning(res.message);
        }
        this.delDrillModal = false;
        this.getSurveyContentList(this.questionnaireId);
      });
    },
    selectQuestion(item) {},
    getSurveyContentList(id) {
      let params = {
        questionnaireId: id,
        pageSize: 2147483646
      };
      getSurveyContentList(params).then((res) => {
        if (res.code == 1) {
          this.objList = res.data.items;
          this.objTotal = res.data.total;
          this.index = this.objTotal + 1;
          this.objList.forEach((item) => {
            item.options.forEach((items) => {
              this.$set(items, 'no', items.label);
            });
            this.$set(item, 'answers', item.options);
            this.$set(item, 'name', item.description);
            if (item.type === 0) {
              this.$set(item, 'modeCode', 1);
            } else if (item.type === 2) {
              this.$set(item, 'modeCode', 6);
              this.$set(item, 'description', item.description);
            } else {
              this.$set(item, 'modeCode', 2);
            }
          });
        } else {
          this.$Message.warning('查询问卷内题目失败');
        }
        this.initContentData();
      });
    },
    contentBtn() {
      this.$refs['contentFormValidate'].validate((valid) => {
        if (valid) {
          if (this.isadd == true) {
            this.addObjContent();
          } else {
            this.modObjContent();
          }
        } else {
          this.$Message.error('请完善信息!');
        }
      });
    },
    modObjContent() {
      let copyObj = JSON.parse(JSON.stringify(this.ContentDto));
      if (copyObj.type === 1 || copyObj.type === 0) {
        // 单选多选，需要把选项的内容格式化
        copyObj.options.forEach((answer, index) => {
          answer.label = index + 1;
          answer.description = '[' + this.filterIndex(index + 1) + ']' + answer.description;
        });
      }
      updateSurveyContent(copyObj).then((res) => {
        if (res.code == 1) {
          this.$Message.success('修改题目成功');
          this.getSurveyContentList(this.questionnaireId);
          (this.isadd = false), this.handleReset1();
        } else {
          this.$Message.warning(res.message);
        }
      });
    },
    addObjContent() {
      let copyObj = JSON.parse(JSON.stringify(this.ContentDto));
      if (copyObj.type === 1 || copyObj.type === 0) {
        // 单选多选，需要把选项的内容格式化
        copyObj.options.forEach((answer, index) => {
          answer.label = index + 1;
          answer.description = '[' + this.filterIndex(index + 1) + ']' + answer.description;
        });
      }
      createSurveyContent(copyObj).then((res) => {
        if (res.code == 1) {
          this.$Message.success('创建题目成功');
          this.getSurveyContentList(this.questionnaireId);
        } else {
          this.$Message.warning(res.message);
        }
      });
    },
    handleRemove(index,item) {
      this.ContentDto.options.splice(index, 1);
      this.optionsIndex--;
      this.ContentDto.options.forEach((item, index) => {
        item.label = index + 1;
      });
       if(item && item.id){
        deleteContentOption(item.id).then(res=>{
          if(res.code == 1){
            // this.$Message.success();
          }else{
            this.$Message.warning(res.message)
          }
        })
      }
      console.log(this.ContentDto.options, 'this.ContentDto.options');
    },
    addAnswers(item,type) {
      console.log('🚀 addAnswers ~ item,type:', item,type)
      console.log('🚀 this.ContentDto:', this.ContentDto)
      this.optionsIndex++;
      let obj = {
        description: '',
        label: this.optionsIndex,
        questionnaireId: this.questionnaireId,
      }
      if(type && item.id){
        obj.contentId = item.id
      }
      this.ContentDto.options.push(obj);
      // this.ContentDto.options.push({
      //   description: '',
      //   label: this.optionsIndex,
      //   questionnaireId: this.questionnaireId,
      //   contentId: this.ContentDto.id || ''
      // });
    },
    filterIndex(val) {
      let str = '';
      switch (val) {
        case 1:
          str = 'A';
          break;
        case 2:
          str = 'B';
          break;
        case 3:
          str = 'C';
          break;
        case 4:
          str = 'D';
          break;
        case 5:
          str = 'E';
          break;
        case 6:
          str = 'F';
          break;
        case 7:
          str = 'G';
          break;
        case 8:
          str = 'H';
          break;
        case 9:
          str = 'I';
          break;
        case 10:
          str = 'J';
          break;
        case 11:
          str = 'K';
          break;
        case 12:
          str = 'L';
          break;
        default:
          str = '';
          break;
      }
      return str;
    },
    changeAnswerTxt(val) {
      if (val == 2) {
        this.ContentDto.options = [];
      } else {
        this.ContentDto.options = [
          {
            description: '',
            label: 1,
            questionnaireId: this.questionnaireId
          },
          {
            description: '',
            label: 2,
            questionnaireId: this.questionnaireId
          },
          {
            description: '',
            label: 3,
            questionnaireId: this.questionnaireId
          },
          {
            description: '',
            label: 4,
            questionnaireId: this.questionnaireId
          }
        ];
      }
    },
    showAddContent(row) {
      this.questionnaireId = row.id;
      this.contentModal.show = true;
      this.getSurveyContentList(this.questionnaireId);
      this.isadd == true;
    },
    initContentData() {
      let _this = this;
      this.ContentDto = {
        description: '',
        label: _this.index,
        type: '',
        questionnaireId: this.questionnaireId,
        options: [
          {
            description: '',
            label: 0,
            questionnaireId: this.questionnaireId
          }
        ]
      };
      this.$refs.contentFormValidate.resetFields()
    },
    //用户管理
    membersManage(row) {
      this.$router.push({
        name: 'questionnaireUser',
        query: {
          id: row.id,
          name: row.name,
          page: this.search.pageIndex,
          creator: row.creator,
          sceneId: row.sceneId
        }
      });
    },
    //重置表单
    handleReset(type) {
      this.$refs.formValidate.resetFields();
    },
    handleReset1(type) {
      this.$refs.contentFormValidate.resetFields();
    },
    // 初始化创建数据
    initData() {
      this.formValidate = {
        name: '',
        description: '',
        available: 0,
        sceneId: ''
      };
    },
    //创建弹窗
    showAddAndUpdate(type, row) {
      this.getSceneList();
      this.modal.show = true;
      if (type == 'add') {
        // 没有数据则是创建动作
        this.modal.title = `创建${this.pageBtnTxt}`;
        this.modal.isAdd = true;
        this.initData();
      } else {
        // 修改动作
        this.modal.title = `修改.pageBtnTxt}`;
        this.modal.isAdd = false;
        (this.formValidate.name = row.name),
          (this.formValidate.description = row.description),
          (this.formValidate.available = row.available);
        this.formValidate.id = row.id;
        this.formValidate.sceneId = row.sceneId;
      }
    },
    formBtn() {
      if (this.modal.isAdd == true) {
        this.addQuestionnaire();
      } else {
        this.modQuestionnaireSurvey();
      }
    },
    //创建
    addQuestionnaire(name) {
      this.$refs['formValidate'].validate((valid) => {
        if (valid) {
          createQuestionnaireSurvey(this.formValidate).then((res) => {
            if (res.code == 1) {
              this.$Message.success('添加成功');
              this.getQuestionnaire();
              // if(this.formValidate.sceneId!=''){
              //     this.getaccessgrouplist()
              // }
            } else {
              this.$Message.warning(res.message);
            }
          });
          this.modal.show = false;
        } else {
          this.$Message.error('请完善信息!');
        }
      });
    },
    //修改
    modQuestionnaireSurvey() {
      updateQuestionnaireSurvey(this.formValidate).then((res) => {
        if (res.code == 1) {
          this.$Message.success('修改成功');
          this.getQuestionnaire();
          if (this.formValidate.sceneId != '') {
            this.getaccessgrouplist();
          }
        } else {
          this.$Message.warning(res.message);
        }
        this.modal.show = false;
      });
    },
    //删除
    delQuestionnaireSurvey(id) {
      deleteQuestionnaireSurvey(id).then((res) => {
        if (res.code == 1) {
          this.$Message.success('删除成功');
          this.getQuestionnaire();
        } else {
          this.$Message.success(res.message);
        }
      });
    },
    //查询问卷列表
    getQuestionnaire(pageIndex) {
      this.loading = true;
      if (pageIndex) {
        this.search.pageIndex = pageIndex;
        this.search.creator = this.creatByMeModal ? this.USER_ID : undefined;
      }
      getQuestionnaireSurveyList(this.search).then((res) => {
        if (res.code == 1) {
          this.list = res.data.items;
          this.total = res.data.total;
          console.log('🚀 this.total:', this.total)
        } else {
          this.$Message.warning(res.message);
        }
        this.loading = false;
      }).catch(error => {
        this.loading = false;
      });
    },
    //刷新按钮
    refreshSurveyContentList() {
      this.search.name = '';
      this.creatByMeModal = false
      this.getQuestionnaire(1);
    },
    changePage(val) {
      this.loading = true;
      this.search.pageIndex = val;
      this.getQuestionnaire();
    },
    //按钮权限
    setReBtnStatus(params) {
      let userid = params.creator;
      let dis = userid != this.USER_ID;
      return dis;
    },
    visibleChange(type) {
      if (!type) {
        this.$refs.formValidate.resetFields();
      }
    }
  }
};
</script>

<style scoped>
.class-title-all {
  font-size: 16px;
  cursor: pointer;
  color: var(--default-color-level2);
}

.active {
  color: var(--default-color);
  font-size: 22px;
  font-weight: 600;
}
.class-title-wrap {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}
</style>
